package m2_work;

import java.io.IOException;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;

public class Consumer {
    public static void main(String[] args) throws Exception {
        //连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.126.129");
        factory.setUsername("admin");
        factory.setPassword("admin");

        Channel channel = factory.newConnection().createChannel();

        //定义队列,第二个参数设置为true，表示该队列是持久化队列
        channel.queueDeclare("task_queue",true,false,false,null);

        DeliverCallback deliverCallback = new DeliverCallback(){

            @Override
            public void handle(String consumerTage, Delivery message) throws IOException {
                String msg = new String(message.getBody());
                System.out.println("收到：" + msg);
                for(int i=0;i<msg.length();i++){
                    if(msg.charAt(i)=='.'){
                        try {
                            Thread.sleep(1000);//遇到'.'暂停一秒
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                //手动ACK需要发送回执
                channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
                System.out.println("消息处理完成\n");
            }
        };

       CancelCallback cancelCallback = new CancelCallback(){

            @Override
            public void handle(String s) throws IOException {

            }
        };

       //QOS:quality of service
        // 理解：每次抓取的消息数量
        //如果设置成1，每次只抓取一条消息，这条消息处理完之前，不会继续抓取下一条
        //必须在手动ACK模式下才有效
        channel.basicQos(1);

        //消费数据,第二个参数设置为手动ACK
        channel.basicConsume("task_queue", false,deliverCallback,cancelCallback);
        System.out.println("开始消费数据");
    }
}